package seo.main;

import seo.picker.NumberPicker;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SeoActivity extends Activity {

	protected SeoApplication app;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setTitle(getResources().getString(
				R.string.app_title));
		app = (SeoApplication) getApplication();
		this.initLocationProvider();
		this.inicializarElementos();
		this.showPatentes();
		this.showLocation();
	}

	private void initLocationProvider() {
		app.getLocationProvider().addMessageHandler(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				String newLocationAddress = app.getLocationProvider()
						.getNewLocationAddress();
				if (newLocationAddress != null) {
					app.setLastKnownLocation(app.getLocationProvider()
							.getNewLocation());
					app.setLastKnownLocationAddress(newLocationAddress);
					locationProviderStop();
				}
				showLocation();
			}
		});
	}

	private void locationProviderStop() {
		if (!app.getLocationProvider().isPaused())
			app.getLocationProvider().onStop();
		final Button buttonUpdateLocation = (Button) findViewById(R.id.buttonUpdateLocation);
		buttonUpdateLocation.setText(getResources().getString(
				R.string.buttonUpdateLocation));
		this.showLocation();
	}

	private void locationProviderStart() {
		app.startLocationProvider();
		this.initLocationProvider();
		app.getLocationProvider().start();
	}

	private void showLocation() {
		final TextView locationResults = (TextView) findViewById(R.id.textViewLocationResult);
		final TextView locationCode = (TextView) findViewById(R.id.editTextLocationCode);
		final TextView locationNumbers = (TextView) findViewById(R.id.editTextLocationNumbers);
		final NumberPicker numberPicker = (NumberPicker) findViewById(R.id.numberPickerEstadia);
		if (app.getLocationProvider().isPaused()) {
			String address = app.getLastKnownLocationAddress();
			if (address != null) {
				locationResults.setText(address);
				SeoMessage message = new SeoMessage(getPatenteSelecionada(),
						numberPicker.getValue(), address, app.getDataBase());
				if ((message.getLocationCode() != null)
						&& (message.getLocationNumber() != null)) {
					locationCode.setText(message.getLocationCode());
					locationNumbers.setText(message.getLocationNumber());
				}
			} else
				locationResults.setText(getResources().getString(
						R.string.unknownLocation));
		} else {
			final Button buttonUpdateLocation = (Button) findViewById(R.id.buttonUpdateLocation);
			buttonUpdateLocation.setText(getResources().getString(
					R.string.buttonStopLocation));
			locationResults.setText(getResources().getString(
					R.string.searchingMessage));
		}
	}

	private void inicializarElementos() {
		final Button botonNuevaPatente = (Button) findViewById(R.id.buttonNuevaPatente);
		final EditText textPatenteNueva = (EditText) findViewById(R.id.editTextPatenteNueva);
		botonNuevaPatente.setEnabled(false);
		botonNuevaPatente.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String patenteNueva = textPatenteNueva.getText().toString();
				if (!patenteNueva.equals("")) {
					patenteNueva = patenteNueva.replace("-", " ");
					app.getDataBase().insertarPatente(patenteNueva);
					textPatenteNueva.setText("");
					showPatentes();
				}
			}
		});
		textPatenteNueva.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				if (s.toString().equals(""))
					botonNuevaPatente.setEnabled(false);
				else {
					botonNuevaPatente.setEnabled(true);
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		final Button botonEliminarPatente = (Button) findViewById(R.id.buttonEliminarPatente);
		botonEliminarPatente.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				app.getDataBase().eliminarPatente(getPatenteSelecionada());
				showPatentes();
			}
		});

		final Button buttonUpdateLocation = (Button) findViewById(R.id.buttonUpdateLocation);
		buttonUpdateLocation.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (app.getLocationProvider().isPaused()) {
					locationProviderStart();
				} else {
					locationProviderStop();
				}
			}
		});
		final Button buttonSendSMS = (Button) findViewById(R.id.buttonSendSMS);
		buttonSendSMS.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				final EditText locationCode = (EditText) findViewById(R.id.editTextLocationCode);
				final EditText locationNumber = (EditText) findViewById(R.id.editTextLocationNumbers);
				final NumberPicker numberPicker = (NumberPicker) findViewById(R.id.numberPickerEstadia);
				SeoMessage message = new SeoMessage(getPatenteSelecionada(),
						locationCode.getText().toString(), locationNumber
								.getText().toString(), numberPicker.getValue(), app.getDataBase());
				if (message.isValidMesage()) {
					Intent sendIntent = new Intent(Intent.ACTION_VIEW);
					sendIntent.putExtra("address", SeoMessage.PHONE_NUMBER);
					sendIntent.putExtra("sms_body", message.getMessageText());
					sendIntent.setType("vnd.android-dir/mms-sms");
					startActivity(sendIntent);
				} else {
					Toast.makeText(getBaseContext(), message.getMessageText(),
							Toast.LENGTH_SHORT).show();
				}

			}
		});
	}

	private String getPatenteSelecionada() {
		final Spinner patentes = (Spinner) findViewById(R.id.listPatentes);
		Cursor c = (Cursor) patentes.getSelectedItem();
		if (c != null) {
			return c.getString(c.getColumnIndex("patente"));
		}
		return null;
	}

	private void showPatentes() {
		Cursor c = app.getDataBase().getPatentes();
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_spinner_item, c,
				new String[] { "patente" }, new int[] { android.R.id.text1 });
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		final Spinner patentes = (Spinner) findViewById(R.id.listPatentes);
		patentes.setAdapter(adapter);
		final Button botonEliminarPatente = (Button) findViewById(R.id.buttonEliminarPatente);
		if (c.moveToFirst()) {
			patentes.setEnabled(true);
			botonEliminarPatente.setEnabled(true);
		} else {
			patentes.setEnabled(false);
			botonEliminarPatente.setEnabled(false);
		}
		app.getDataBase().closeDataBase();
	}
}